/**
 * zmn文章模块-文章编辑
 * 文件命名格式：zmn.模块.表/功能.jas
 * @author duanzuocai
 * @since 2018/10/18
 */
layui.define(['form', 'layedit', 'laydate'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var layedit = layui.layedit;
    var laydate = layui.laydate;

    if(json.staff.entryTime != null){
        laydate.render({elem: "#entryTime", type: "datetime", value: new Date(json.staff.entryTime)});
    }else{
        laydate.render({elem: "#entryTime", type: "datetime"});
    }

    if(json.staff.becomeFormalTime != null){
        laydate.render({elem: "#becomeFormalTime", type: "date", value: new Date(json.staff.becomeFormalTime)});
    }else{
        laydate.render({elem: "#becomeFormalTime", type: "date"});
    }

    form.render(null, "zmn-staff-form");

    // 自定义验证规则
    form.verify({
        title: function (value) {
            if (value.length < 2) {
                return "分类名称不能少于2个字符";
            }
        },
        sort: function (value) {
            if (value == null || value == '') {
                return "排序不能为空";
            }
            if (!/^[0-9]+$/.test(value)) {
                return "排序值只能是正整数";
            }
        },
        mobile: function (value) {
            if (value == null || value == "") {
                return;
            }
            if (!new RegExp(/^[0-9]{11}$/).test(value)) {
                return "手机号只能是11位数字";
            }
        },
        loginId: function (value) {
            if (value == null || value == "") {
                return "账号不能为空";
            }

            var reg = new RegExp("^[0-9a-zA-Z]+$");
            if (!reg.test(value)) {
                return "账号只能是数字、字母";
            }
        }
    });


    // 提交
    form.on('submit(zmn-staff-form-submit)', function (obj) {
        var data = obj.field;

        if (data.becomeFormalTime != null && contrastData(data.entryTime, data.becomeFormalTime)) {
            layer.msg("入职时间不能小于转正时间");
            return false;
        }

        var url = "/mc/staff/addEdit.action";

        if (data.deptId == null || data.deptId == "") {
            zmnUtil.alert("请选择部门");
            return false;
        }
        if (data.deptId.split(",").length > 1) {
            zmnUtil.alert("部门只能选择一个");
            return false;
        }


        var openId = layer.open({type: 3});

        var roles = document.getElementsByName("roles");
        var rolesStr = "";
        for (var i = 0; i < roles.length; i++) {
            if (!roles[i].checked) {
                continue;
            }
            if (rolesStr != "") {
                rolesStr += ",";
            }
            rolesStr += roles[i].value;
        }

        data["roles"] = rolesStr;
        if(json.staff.staffId == null || json.staff.staffId == 0){
            data["status"] = 2;
        }

        if(data["staffStatus"] < 3){
            data["status"] = 2;
        }

        $.ajax({
            async: false,
            type: "POST", url: url,
            contentType: "application/json", dataType: "json", data: JSON.stringify(data),
            success: function (json) {
                layer.close(openId);
                parent.layui.layer.msg(json.message);
                if (json.status == 200) {
                    parent.layui.element.tabChange('layadmin-layout-tabs', "/categ/attr/list.action?categId=" + json.id);
                    parent.layui.element.tabDelete('layadmin-layout-tabs', window.location.pathname + window.location.search);
                }
            },
            error: function () {
                layer.close(openId);
            }
        })
        return false;
    });

    let formSelects = layui.formSelects;
    form.on("select(companyId)", function (obj) {
        if (zmnUtil.isNull(obj) || obj.value == 0) {
            return;
        }
        initSelect(formSelects, obj.value);
        layui.formSelects.render();
    });

    if (json.staff.companyId) {
        initSelect(formSelects, json.staff.companyId);
    }

    function contrastData(val1, val2) {
        let time = new Date(val1).getTime();
        let date1 = new Date(val2).getTime();

        if (time > date1) {
            return true;
        }
        return false;
    }

    //对外暴露的接口
    exports('art_staff_detail', {});
});

function initSelect(formSelects, companyId) {

    formSelects.config('deptId', {
        keyName: 'value',
        keyVal: 'key',
        keyChildren: 'list',
        success: function (id, url, val, result) {
            formSelects.value('deptId', [json.deptIds]);
            console.log(json.deptIds);
        },
        error: function (id, url, val, err) {
            console.log(id + ":" + err);
        }
    });

    /**
     * 1.多选数据赋值
     *
     * formSelects.data(ID, type, config);
     *
     * @param ID            xm-select的值
     * @param type          'local' | 'server', 本地数据或者远程数据
     * @param config        配置项
     *          arr             本地数据数组
     *          url             远程数据链接
     *          keyword         远程数据搜索内容, 其他附加数据可以使用 formSelects.config设置
     *          linkage         是否为联动多选（就是把上级地扯关联一起显示/选择，true时必须全择到最底层一条线才行）
     *          linkageWidth    联动多选没级宽度
     */
    formSelects.data('deptId', 'server', {
        url: '/mc/dept/findDeptByCompanyId.action?companyId=' + companyId,
        linkage: false,
        linkageWidth: 130
    });

    formSelects.render();
}